package com.showtao.front.controller;

import java.util.ArrayList;
import java.util.List;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.showtao.common.dto.ResultDto;
import com.showtao.common.dto.ResultDtoFactory;
import com.showtao.common.dto.widget.DataTablesRequestDto;
import com.showtao.common.dto.widget.DataTablesResponseDto;
import com.showtao.common.enumeration.EErrorCode;
import com.showtao.common.exception.BizServiceException;
import com.showtao.common.validation.ValidateException;
import com.showtao.front.domain.Article;
import com.showtao.front.domain.ArticleStatus;
import com.showtao.front.domain.Catalog;
import com.showtao.front.domain.ProductCategory;
import com.showtao.front.dto.ArticleDto;
import com.showtao.front.dto.CatalogDto;
import com.showtao.front.dto.upstream.MessageSavingDto;
import com.showtao.front.service.ContentService;
import com.showtao.front.service.ProductService;

@Controller
public class ContentViewController {

	@Autowired
	private ContentService contentService;
	@Autowired
	private ProductService productService;

	@RequestMapping(value = "/content/{alias}")
	public String viewContentList(@PathVariable("alias") String alias,
			Model model) {
		Catalog c = contentService.getCatalogByAlias(alias);
		if (c == null) {
			throw new BizServiceException(EErrorCode.COMM_INTERNAL_ERROR,
					"不存在alias=" + alias + "的Catalog对象");
		}
		List<Catalog> subCatalogs = new ArrayList<Catalog>();
		if (c.getParent() == null) {
			if ("about".equals(c.getAlias())) {
				model.addAttribute("aboutCatalogs", null);
			}
			if ("auditorium".equals(c.getAlias())){
			    model.addAttribute("allowAsk", true);
			}
			subCatalogs = contentService.getSubCatalogs(c.getId());
			model.addAttribute("catalog", c);
			model.addAttribute("menuItem", c.getAlias());
		} else {
		    if("about".equals(c.getParent().getAlias())){
		        model.addAttribute("aboutCatalogs", null);
		    }
		    if ("auditorium".equals(c.getParent().getAlias())){
                model.addAttribute("allowAsk", true);
            }
			subCatalogs = contentService.getSubCatalogs(c.getParent().getId());
			model.addAttribute("catalog", c.getParent());
			model.addAttribute("menuItem", c.getParent().getAlias());
		}
		model.addAttribute("subCatalogs", subCatalogs);
		model.addAttribute("selectedAlias", alias);
		long count = contentService.countArticlesByCatalogAndStatus(c,
				ArticleStatus.PUBLISHED);
		if (count == 1) {
			model.addAttribute("article", contentService
					.getTheFirstArticleByCatalogAndStatus(c,
							ArticleStatus.PUBLISHED));
		} else if (c.getParent() == null && subCatalogs.size() != 0) {
			return "redirect:/content/" + subCatalogs.get(0).getAlias();
		} else {
			model.addAttribute("catalogId", c.getId());
		}
		return "content/index";
	};

	@RequestMapping(value = "/article/{articleId}")
	public String viewSingleArticle(
			@PathVariable("articleId") Long articleId,
			Model model) {
		Article a = contentService.getArticle(articleId);
		if (a == null) {
			throw new BizServiceException(EErrorCode.COMM_INTERNAL_ERROR,
					"不存在ID=" + a + "的Artilce对象");
		}
		Catalog c = a.getCatalog();
		List<Catalog> subCatalogs = new ArrayList<Catalog>();
		if (c.getParent() == null) {
			if ("about".equals(c.getAlias())) {
				model.addAttribute("aboutCatalogs", null);
			}
			subCatalogs = contentService.getSubCatalogs(c.getId());
			model.addAttribute("catalog", c);
			model.addAttribute("menuItem", c.getAlias());
		} else {
		    if("about".equals(c.getParent().getAlias())){
                model.addAttribute("aboutCatalogs", null);
            }
			subCatalogs = contentService.getSubCatalogs(c.getParent().getId());
			model.addAttribute("catalog", c.getParent());
			model.addAttribute("menuItem", c.getParent().getAlias());
		}
		model.addAttribute("subCatalogs", subCatalogs);
		model.addAttribute("selectedAlias", c.getAlias());
		model.addAttribute("article", a);
		return "content/article";
	};

	@RequestMapping(value = "/catalogs/{catalogId}/articles", method = RequestMethod.POST)
	@ResponseBody
	public DataTablesResponseDto<ArticleDto> doSearchArticles(
			@PathVariable("catalogId") Long catalogId,
			@Valid @RequestBody DataTablesRequestDto requestDto,
			BindingResult result) throws Exception {
		// 判断是否有验证错误
		if (result.hasErrors()) {
			throw new ValidateException(result);
		}
		// 组装Pageable
		Pageable pageable = requestDto.toPagable();
		Page<ArticleDto> page = contentService.findArticlesByCatalogId(
				catalogId, pageable);
		DataTablesResponseDto<ArticleDto> responseDto = new DataTablesResponseDto<ArticleDto>();
		return responseDto.populateFromPage(page, requestDto.getDraw());
	}
	
	@RequestMapping(value = "/message", method = RequestMethod.POST)
	@ResponseBody
	public ResultDto doSaveMessage(
	        @Valid @RequestBody MessageSavingDto dto,
			BindingResult result) throws Exception {
		// 判断是否有验证错误
		if (result.hasErrors()) {
			throw new ValidateException(result);
		}
		contentService.saveMessage(dto);
		return ResultDtoFactory.toAck("留言保存成功");
	}

	@ModelAttribute("navCatalogs")
	public List<CatalogDto> findNavCatalogs() {
		List<CatalogDto> result = new ArrayList<CatalogDto>();
		List<Catalog> cts = contentService.findNavCatalogs();
		for (Catalog ct : cts) {
			result.add(CatalogDto.from(ct));
		}
		return result;
	}

	@ModelAttribute("categories")
	public List<ProductCategory> findProductCategories() {
		return productService.findAllProductCategories();
	}

	@ModelAttribute("aboutCatalogs")
	public List<CatalogDto> findAboutNavCatalogs() {
		List<CatalogDto> result = new ArrayList<CatalogDto>();
		List<Catalog> cts = contentService.getSubCatalogsByAlias("about");
		for (Catalog ct : cts) {
			result.add(CatalogDto.from(ct));
		}
		return result;
	}
}
